package com.atguigu.Sink;

import com.atguigu.been.WaterSensor;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @author wky
 * @create 2021-07-14-20:23
 */
public class Sink_Custom {
    public static void main(String[] args) throws Exception {
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_5", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_6", 1607527994000L, 50));


        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        DataStreamSource<WaterSensor> streamSource = senv.fromCollection(waterSensors);
        streamSource.addSink(new RichSinkFunction<WaterSensor>() {
            Connection coon ;
            PreparedStatement ps;
            @Override
            public void open(Configuration parameters) throws Exception {
                 coon = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test?useSSL=false", "root", "123456");
                  ps = coon.prepareStatement("insert into sensor values(?,?,?)");
            }

            @Override
            public void close() throws Exception {
                ps.close();
                coon.close();
            }

            @Override
            public void invoke(WaterSensor value, Context context) throws Exception {
                ps.setString(1, value.getId());
                ps.setLong(2, value.getTs());
                ps.setInt(3, value.getVc());
                ps.execute();
            }

        });
        senv.execute();

    }
}
